/**
 * Created by Administrator on 2017/8/24 0024.
 */
var _ = require("underscore"),
    common = {
    dateFormatter: function (dateTime,fmt) {
        fmt = fmt || "yyyy-MM-dd hh:mm:ss";

        if(_.isString(dateTime)) {
            dateTime = this.parseDate(dateTime);
        }

        if(!_.isDate(dateTime)) {
            return dateTime;
        }

        var o = {
            "M+" : dateTime.getMonth() + 1,                   //月份
            "d+" : dateTime.getDate(),                    //日
            "h+" : dateTime.getHours(),                   //小时
            "m+" : dateTime.getMinutes(),                 //分
            "s+" : dateTime.getSeconds(),                 //秒
            "q+" : Math.floor((dateTime.getMonth()+3)/3), //季度
            "S"  : dateTime.getMilliseconds()             //毫秒
        };

        if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (dateTime.getFullYear()+"").substr(4 - RegExp.$1.length));
        }

        for(var k in o) {
            if(new RegExp("("+ k +")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
            }
        }

        return fmt;
    },
    /**
     * **字符串转换成日期对象**
     * @method parseDate
     * @param text{string}  传入的日期字符串 支持yyyy-MM-dd hh:mm:ss、 yyyyMMdd hh:mm:ss 、 yyyy/MM/dd hh:mm:ss格式的字符串
     * @returns {Date} 根据日期字符串返回日期
     */
    parseDate:function(text){
        var dt = text.split(" "),
            hh = 0,mm = 0,ss = 0,
            matchD,year,month,dd,hmsStr,hms,ymdStr = dt[0];
        if(dt.length == 2) {
            hmsStr = dt[1];
        }

        if(matchD = ymdStr.match(/^(\d{4})\D(\d{1,2})\D(\d{1,2})$/)){
            year = matchD[1];
            month = matchD[2];
            dd = matchD[3];
        }else{
            if(ymdStr.length === 8){
                year = ymdStr.substring(0,4);
                month = ymdStr.substring(4,6);
                dd = ymdStr.substring(6,8);
            }
        }
        if(hmsStr){
            hms = hmsStr.match(/^(\d{2})\D(\d{2})\D(\d{2})/);
            hh = hms[1];
            mm = hms[2];
            ss = hms[3];
        }

        return new Date(year, month - 1, dd, hh, mm, ss);
    }
};
module.exports = common;